package com.ahdy.tool;

import java.io.*;

public class AudioConvertUtil {
    /**
     * mp3转wav（16kHz单声道16bit）
     * 
     * @param mp3Bytes mp3音频字节
     * @return wav音频字节
     */
    public static byte[] mp3ToWav(byte[] mp3Bytes) throws IOException, InterruptedException {
        File mp3File = File.createTempFile("audio_", ".mp3");
        File wavFile = File.createTempFile("audio_", ".wav");
        try (FileOutputStream fos = new FileOutputStream(mp3File)) {
            fos.write(mp3Bytes);
        }
        // ffmpeg命令
        String cmd = String.format("ffmpeg -y -i \"%s\" -ar 16000 -ac 1 -sample_fmt s16 \"%s\"",
                mp3File.getAbsolutePath(), wavFile.getAbsolutePath());
        Process process = Runtime.getRuntime().exec(cmd);
        process.waitFor();

        // 读取wav文件
        byte[] wavBytes = java.nio.file.Files.readAllBytes(wavFile.toPath());
        // 删除临时文件
        mp3File.delete();
        wavFile.delete();
        return wavBytes;
    }
}